﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Windows.Controls.Primitives;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;

namespace MoneyBook.Interactivity {
    public class DefaultButtonBehavior : Behavior<FrameworkElement> {

        public ButtonBase TargetButton {
            get { return (ButtonBase)GetValue(TargetButtonProperty); }
            set { SetValue(TargetButtonProperty, value); }
        }

        public static readonly DependencyProperty TargetButtonProperty =
            DependencyProperty.Register("TargetButton", typeof(ButtonBase), typeof(DefaultButtonBehavior), null);

        private void AssociatedObject_KeyDown(object sender, KeyEventArgs e) {
            if (e.Key != Key.Enter || this.TargetButton == null) {
                return;
            }

            //TODO:こちらで止めるのではなく、TextBoxとかにBehaviorを設定してそこで Enter をハンドルしきるほうがよさげ。
            if (e.OriginalSource is TextBox) {
                if (((TextBox)e.OriginalSource).AcceptsReturn) {
                    return;
                }
            }

            AutomationPeer peer = ButtonBaseAutomationPeer.CreatePeerForElement(this.TargetButton);
            //peer.SetFocus();

            Dispatcher.BeginInvoke(() => {
                if (!this.TargetButton.IsEnabled) return;

                ((IInvokeProvider)peer.GetPattern(PatternInterface.Invoke)).Invoke();
            });
            e.Handled = true;
        }

        protected override void OnAttached() {
            base.OnAttached();
            this.AssociatedObject.KeyDown += AssociatedObject_KeyDown;
        }

        protected override void OnDetaching() {
            base.OnDetaching();
            this.AssociatedObject.KeyDown -= AssociatedObject_KeyDown;
        }
    }
}
